#!/bin/bash

# ---------- 配置区 ----------
cache_file="/tmp/dynv6_ip_cache.conf"    # 键值对缓存文件
dyndoman="baoyuan.dynv6.net"            # 动态域名
dyn_token="M9A6JAHs4dTZxVCHWwJfqd1GytzYwE"        # 新增API令牌配置
enable_ipv4=1    # 启用IPv4更新 (1启用/0禁用)
enable_ipv6=1    # 启用IPv6更新 (1启用/0禁用)
# ---------------------------


execute_update4() {
    echo "正在通过API更新IPv4记录..."
    # 添加hostname参数并严格检查响应
    response=$(curl -4 -sG --data-urlencode "hostname=${dyndoman}" \
        "https://ipv4.dynv6.com/api/update?ipv4=${ipv4addr}&token=${dyn_token}")
    
    # 严格检查响应内容
    if [[ $? -eq 0 && "$response" == *"addresses updated"* ]]; then
        echo "IPv4 API更新成功：$response"
        return 0
    else
        echo "IPv4 API更新失败：${response:-无响应}"
        return 1
    fi
}

execute_update6() {
    echo "正在通过API更新IPv6记录..."
    # 添加hostname参数并严格检查响应
    response=$(curl -6 -sG --data-urlencode "hostname=${dyndoman}" \
        "https://ipv6.dynv6.com/api/update?ipv6=${ipv6addr}&token=${dyn_token}")
    
    # 严格检查响应内容
    if [[ $? -eq 0 && "$response" == *"addresses updated"* ]]; then
        echo "IPv6 API更新成功：$response"
        return 0
    else
        echo "IPv6 API更新失败：${response:-无响应}"
        return 1
    fi
}

# ---------- 主程序 ----------
# 获取当前IP
ipv4addr=$(curl -4 -s https://ipv4.ident.me || curl -4 -s https://ipinfo.io/ip || curl -s https://4.ipw.cn)
ipv6addr=$(curl -6 -s https://ipv6.ident.me || curl -6 -s https://ipinfo.io/ip || curl -s https://6.ipw.cn)

# 读取缓存函数
read_cache() {
    if [[ -f "$cache_file" ]]; then
        old_ipv4=$(grep '^old_ipv4=' "$cache_file" | cut -d'=' -f2)
        old_ipv6=$(grep '^old_ipv6=' "$cache_file" | cut -d'=' -f2)
    else
        old_ipv4=""
        old_ipv6=""
    fi
}

# 主逻辑
read_cache  # 读取旧IP

echo "[DEBUG] 缓存IPv4: ${old_ipv4:-无}"
echo "[DEBUG] 缓存IPv6: ${old_ipv6:-无}"
echo "[DEBUG] 当前IPv4: $ipv4addr"
echo "[DEBUG] 当前IPv6: $ipv6addr"

# 初始化新IP变量
new_ipv4="$old_ipv4"
new_ipv6="$old_ipv6"
any_success=0

# 检测到变化才执行更新
    
if [[  $enable_ipv4 -eq 1 && "$ipv4addr" != "$old_ipv4" ||  $enable_ipv6 -eq 1 && "$ipv6addr" != "$old_ipv6" ]]; then
    echo "检测到IP变化，开始更新..."
    
    # IPv4更新逻辑
    if [[ $enable_ipv4 -eq 1 && "$ipv4addr" != "$old_ipv4" ]]; then
        if execute_update4; then
            new_ipv4="$ipv4addr"
            any_success=1
        fi
    fi
    
    # IPv6更新逻辑
    if [[ $enable_ipv6 -eq 1 && "$ipv6addr" != "$old_ipv6" ]]; then
        if execute_update6; then
            new_ipv6="$ipv6addr"
            any_success=1
        fi
    fi
    
    # 缓存写入逻辑
    if [[ $any_success -eq 1 ]]; then
        printf "old_ipv4=%s\nold_ipv6=%s\n" "$new_ipv4" "$new_ipv6" > "$cache_file"
        echo "成功更新缓存"
    else
        echo "所有更新均失败，缓存未修改"
    fi
    
else
    echo "IP未变化，无需操作"
fi
